package order

import (
	"enjoy_xxz/formdata"
	"enjoy_xxz/internal/model/database/mysql"
	"enjoy_xxz/pkg"
	"gorm.io/gorm"
)

type OrderGoods struct {
	gorm.Model
	OrderID  int64  `gorm:"type:int;comment:订单ID"`
	GoodID   int64  `gorm:"type:int;comment:商品ID"`
	Title    string `gorm:"type:varchar(255);comment:商品标题"`
	Img      string `gorm:"type:json;comment:商品图片链接"`
	SKUId    int64  `gorm:"type:int;comment:商品SKU ID"`
	Quantity int64  `gorm:"type:int;comment:商品购买数量"`
	Price    string `gorm:"type:decimal(10,2);comment:商品价格"`
}

// 创建订单商品
func (o *OrderGoods) CreateOrderGoods() error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Create(&o).Error
	})
}

// 查询订单商品信息
func (o *OrderGoods) GetOrderGoodsByIds(id int64) (infoList formdata.OrderGoodsInfo, err error) {
	var list []OrderGoods
	return infoList, mysql.WithMysql(func(db *gorm.DB) error {
		//查询订单是否存在
		var oo Order
		err = db.Model(&Order{}).Where("id = ?", id).First(&oo).Error
		if err != nil {
			return err
		}
		//查询商品
		err = db.Where("order_id = ? ", id).Find(&list).Error
		if err != nil {
			return err
		}
		var goodsList []formdata.OrderGoodsInfos
		for _, val := range list {
			//解析图片
			images := pkg.GetImages(val.Img)
			goodsList = append(goodsList, formdata.OrderGoodsInfos{
				GoodsId:  val.GoodID,
				SkuId:    val.SKUId,
				Title:    val.Title,
				Img:      images,
				Price:    val.Price,
				Quantity: val.Quantity,
			})
		}
		// 格式化时间为字符串
		formattedTime := oo.CreatedAt.Format("2006-01-02 15:04:05") // 根据需要调整格式
		infoList = formdata.OrderGoodsInfo{
			OrderID:        int64(oo.ID),
			OrderNo:        oo.No,
			CreateTime:     formattedTime,
			Amount:         oo.Amount,
			OrderGoodsInfo: goodsList,
		}

		return nil

	})
}
